// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
  throwOnNotFound: false
})
const $ = db.command.aggregate
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const {
    pageNo,
    pageSize,
    date,
    community,
    buildingNo,
    unitNo,
    keyword
  } = event
  const offset = (pageNo - 1) * pageSize
  const match = {
    'baseInfo.community': _.neq(null)
  }
  if (community) {
    match['baseInfo.community'] = community
  }
  if (buildingNo) {
    match['baseInfo.buildingNo'] = buildingNo
  }
  if (unitNo) {
    match['baseInfo.unitNo'] = unitNo
  }
  if (keyword) {
    match['baseInfo.roomNo'] = db.RegExp({
      regexp: `.?${keyword}.?`,
      options: 'i',
    })
  }

  const {
    list
  } = await db.collection('user')
    .aggregate()
    .match(match)
    .lookup({
      from: 'record',
      let: {
        userId: "$_id"
      },
      pipeline: $.pipeline().match(_.expr($.and([
          $.eq(['$_openid', '$$userId']),
          $.eq(['$date', date]),
          $.neq(['$deleted', 1])
        ])))
        .project({
          _openid: 0
        }).done(),
      as: 'records'
    })
    .sort({
      'baseInfo.community': 1,
      'baseInfo.buildingNo': 1,
      'baseInfo.unitNo': 1
    })
    .skip(offset)
    .limit(pageSize)
    .end()
  // 设置用户小区信息
  const communityIds = Array.from(new Set(list.map(u => u.baseInfo.community)))
  const {
    data: communityList
  } = await db.collection('community').where({
    '_id': _.in(communityIds)
  }).get()
  list.forEach(async u => {
    const find = communityList.filter(c => c._id == u.baseInfo.community)
    u.community = find[0]
  })
  // 设置用户家人数量
  const userIds = list.map(u => u._id)
  const {
    list: homemateCountList
  } = await db.collection('homemate').aggregate()
    .match({
      '_openid': _.in(userIds),
      deleted: _.neq(1)
    }).group({
      _id: '$_openid',
      sum: $.sum(1)
    })
    .end()
  list.forEach(async u => {
    const find = homemateCountList.filter(c => c._id == u._id)
    u.homemateCount = find[0].sum
  })

  let homemateIds = []
  // 设置record中的家人信息
  list.map(u => {
    return u.records.map(r => r.homemate)
  }).forEach(a => {
    homemateIds = [...homemateIds, ...a]
  })
  homemateIds = Array.from(new Set(homemateIds))
  const {
    data: homemateList
  } = await db.collection('homemate').where({
    _id: _.in(homemateIds)
  }).get()

  list.forEach(async u => {
    u.records.forEach(async r => {
      const find = homemateList.filter(h => h._id == r.homemate)
      r._homemate = find[0]
    })
  })

  // 获取全体信息
  // 总人数
  const {
    list: hs
  } = await db.collection('user').aggregate()
    .match(match)
    .lookup({
      from: 'homemate',
      let: {
        userId: "$_id"
      },
      pipeline: $.pipeline().match(_.expr($.and([
          $.eq(['$_openid', '$$userId']),
          $.neq(['$deleted', 1])
        ])))
        .project({
          _openid: 0
        }).done(),
      as: 'homemates'
    }).replaceRoot({
      newRoot: {
        count: $.size('$homemates')
      }
    })
    .end()

  const peopleCount = hs.map(h => h.count).reduce((a, b) => a + b, 0)

  // 测试人数
  const {
    list: csCountList
  } = await db.collection('user').aggregate()
    .match(match)
    .lookup({
      from: 'record',
      let: {
        userId: "$_id"
      },
      pipeline: $.pipeline().match(_.expr($.and([
          $.eq(['$_openid', '$$userId']),
          $.eq(['$date', date]),
          $.neq(['$deleted', 1]),
          $.neq(['$tempValue', null])
        ])))
        .project({
          _openid: 0
        })
        .group({
          _id: '$homemate',
          count: $.sum(1)
        })
        .count('count')
        .done(),
      as: 'records'
    })
    .end()

  const csCount = csCountList.map(c => {
    return c.records.map(r => r.count).reduce((a, b) => a + b, 0)
  }).reduce((a, b) => a + b, 0)


  // 危险人数
  const {
    list: errCountList
  } = await db.collection('user').aggregate()
    .match(match)
    .lookup({
      from: 'record',
      let: {
        userId: "$_id"
      },
      pipeline: $.pipeline().match(_.expr($.and([
          $.eq(['$_openid', '$$userId']),
          $.eq(['$date', date]),
          $.neq(['$deleted', 1]),
          $.gte(['$tempValue', 37])
        ])))
        .project({
          _openid: 0
        })
        .group({
          _id: '$homemate',
          count: $.sum(1)
        })
        .count('count')
        .done(),
      as: 'records'
    })
    .end()

  const errCount = errCountList.map(c => {
    return c.records.map(r => r.count).reduce((a, b) => a + b, 0)
  }).reduce((a, b) => a + b, 0)

  console.log(errCount);

  console.log('end');
  return {
    list,
    peopleCount,
    csCount,
    errCount
  }
}